package com.useeinfo.oa.open.admin;

import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.func.excel.ExcelImport;
import com.useeinfo.framework.sugar.func.excel.ExcelImportParam;
import com.useeinfo.framework.sugar.func.excel.ExcelMapImport;
import com.useeinfo.framework.sugar.func.file.FileUtils;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.*;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.FacilityImport;
import com.useeinfo.oa.modules.base.vo.FacilityVO;
import com.useeinfo.oa.modules.logger.biz.FacilityLogBiz;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import com.useeinfo.oa.modules.threadUtil.ThreadUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Auther: 陈炜
 * @Date: 2018/12/18 13:32
 * @Description: 设备批量导入管理action
 */
@Controller
@RequestMapping("/web/admin/facilityImport")
public class FacilityImportAction {
    private final static Logger logger = LoggerFactory.getLogger(FacilityImportAction.class);
    @Autowired
    private FacilityImportBiz facilityImportBiz;
    @Autowired
    private FacilityBiz facilityBiz;
    @Autowired
    private FacilityLogBiz facilityLogBiz;
    @Autowired
    private FacilityGroupBiz facilityGroupBiz;
    @Autowired
    private FacilityCatBiz facilityCatBiz;
    @Autowired
    private AreaBiz areaBiz;
    @Autowired
    private OrganizationBiz organizationBiz;

    @RequestMapping("/list")
    public ModelAndView list() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("pages/admin/facility/facilityImportList");
        return modelAndView;
    }

    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(@RequestParam(value = "pageNo", required = false) String pageNowParam,
                               @RequestParam(value = "pageSize", required = false) String pageSizeParam,
                               @RequestParam(value = "searchCode", required = false) String searchCode,
                               @RequestParam(value = "orderBy", required = false) String orderBy,
                               HttpServletRequest request) {
        QueryParam queryParam = new QueryParam(pageNowParam, pageSizeParam);
        queryParam.getSqlMap().put("searchCode", searchCode);
        if(StringUtils.isNotBlank(orderBy)) {
            queryParam.setSqlOrder("order by " + orderBy);
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        }
        return facilityImportBiz.findJSONList(queryParam);
    }

    @RequestMapping("/importPage")
    public ModelAndView importPage(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        modelAndView.addObject("enterprise",enterprise);
        modelAndView.setViewName("pages/admin/facility/facilityImport");

        return modelAndView;
    }

    /**
     * 删除
     */
    @RequestMapping("/logicRemoveFacilityImport")
    @ResponseBody
    public ResultDto logicRemoveFacilityImport(@RequestParam(value = "id", required = false) String idParam) {

        FacilityImport facilityImport = facilityImportBiz.findModel(StringConverters.ToLong(idParam));
        if(facilityImport==null){
            return ResultUtil.success();
        }else{
            if(!"1".equals(facilityImport.getStatus())){
                return ResultUtil.error("该文件还未完成数据导入，无法删除");
            }
            facilityImportBiz.deleteLogic(facilityImport);
            return ResultUtil.success();
        }
    }

    @RequestMapping("/editPage")
    public ModelAndView editPage(@RequestParam(value = "id", required = false) String id,HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView();
        FacilityImport facilityImport = facilityImportBiz.findModel(StringConverters.ToLong(id));
        modelAndView.addObject("facilityImport",facilityImport);
        modelAndView.setViewName("pages/admin/facility/facilityImportEdit");

        return modelAndView;
    }

    /**
     *上传导入文件
     */
    @RequestMapping("/uploadFacilityImportFile")
    @ResponseBody
    public ResultDto uploadFacilityImportFile(HttpServletRequest request,
                                                           @RequestParam(value = "pic1", required = false) MultipartFile file) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if(enterprise==null){
            return ResultUtil.error("获取企业失败，请更新页面重试");
        }
        if(systemUser==null){
            return ResultUtil.error("获取用户信息失败，请更新页面重试");
        }
        String filePath = Configuration.getConfigurationByName("fileSaveRootPath");
        String savePath = FileUtils.fileUpload(file, "facility", "f",filePath);
        if (org.apache.commons.lang.StringUtils.isEmpty(savePath)) {
            logger.error("文件上传失败");
            return ResultUtil.error();
        }
        String fileWholeName = file.getOriginalFilename();
        String suffix=fileWholeName.substring(fileWholeName.lastIndexOf(".")+1);
        String fileName=fileWholeName.substring(0,fileWholeName.lastIndexOf("."));
        String fileSize = getPrintSize(file.getSize());
        //查总条数
        filePath += filePath.endsWith("/") ? "" : "/";
        // 获取上传excel绝对路径
        String fullPath = filePath + savePath;
        // 获取excel文件中列与对象对应关系
        ExcelImportParam excelImportParam = new ExcelImportParam();
        excelImportParam.setCellPropertyMap(ExcelMapImport.facilityImport());
        // 将excel中数据读入对象
        List<FacilityVO> facilityVOList = ExcelImport.readExcel(fullPath, FacilityVO.class, excelImportParam);
        int totalCount = 0;
        if(CollectionUtils.isNotEmpty(facilityVOList)){
            totalCount = facilityVOList.size();
        }
        FacilityImport facilityImport = new FacilityImport();
        facilityImport.setFileName(fileName);
        facilityImport.setFileSuffix(suffix);
        facilityImport.setFileWholeName(fileWholeName);
        facilityImport.setFileSize(fileSize);
        facilityImport.setFilePath(savePath);
        facilityImport.setTotalCount(totalCount);
        facilityImport.setFinishCount(0);
        facilityImport.setErrorCount(0);
        facilityImport.setEnterprise(enterprise);
        facilityImport.setSystemUserId(systemUser.getId());
        facilityImport.setSystemUserName(systemUser.getUserName());
        facilityImportBiz.addOrUpdate(facilityImport);
        ThreadUtils.importFacilityThread(facilityImportBiz,facilityBiz,facilityLogBiz,facilityGroupBiz,facilityCatBiz,areaBiz,organizationBiz,facilityImport);
        return ResultUtil.success();
    }

    /**
     *byte转化为KB MB等格式的大小
     */
    public static String getPrintSize(long size) {
        //如果字节数少于1024，则直接以B为单位，否则先除于1024，后3位因太少无意义
        if (size < 1024) {
            return String.valueOf(size) + "B";
        } else {
            size = size / 1024;
        }
        //如果原字节数除于1024之后，少于1024，则可以直接以KB作为单位
        //因为还没有到达要使用另一个单位的时候
        //接下去以此类推
        if (size < 1024) {
            return String.valueOf(size) + "KB";
        } else {
            size = size / 1024;
        }
        if (size < 1024) {
            //因为如果以MB为单位的话，要保留最后1位小数，
            //因此，把此数乘以100之后再取余
            size = size * 100;
            return String.valueOf((size / 100)) + "."
                    + String.valueOf((size % 100)) + "MB";
        } else {
            //否则如果要以GB为单位的，先除于1024再作同样的处理
            size = size * 100 / 1024;
            return String.valueOf((size / 100)) + "."
                    + String.valueOf((size % 100)) + "GB";
        }
    }

}
